<template>
  <div class="app-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <el-button type="primary" @click="handleClear">一键清空</el-button>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </div>
      </template>

      <!-- 搜索表单 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="订单状态">
          <el-select style="width: 200px;" v-model="searchForm.status" placeholder="请选择订单状态" clearable>
            <el-option value="全部订单" label="全部订单" />
            <el-option value="未支付" label="未支付" />
            <el-option value="取消" label="已取消" />
            <el-option value="待出行" label="待出行" />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="数据状态">
          <el-select style="width: 200px;" v-model="searchForm.dataStatus" placeholder="请选择数据状态" clearable>
            <el-option :value="-1" label="全部状态" />
            <el-option :value="0" label="正常" />
            <el-option :value="1" label="需修改" />
          </el-select>
        </el-form-item> -->
        <el-form-item label="年月">
          <el-input v-model="searchForm.keyword" placeholder="请输入年月搜索" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button v-if="pagination.size > 10" type="success" @click="handleOptimizeAll"
            :loading="optimizeAllLoading">
            一键优化当前页
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 数据表格 -->
      <el-table v-loading="loading" :data="tableData" border style="width: 100%">
        <el-table-column prop="mon" label="年月" />
        <el-table-column prop="pay" label="金额" />
        <el-table-column prop="da" label="天" />
        <el-table-column prop="a" label="起点" />
        <el-table-column prop="d" label="起点补充" />
        <el-table-column prop="qud" label="渠道" />
        <el-table-column prop="tim" label="时间" />
        <el-table-column prop="b" label="终点" />
        <el-table-column prop="c" label="终点补充" />
        <el-table-column prop="zf" label="支付/取消" />

        <el-table-column label="状态">
          <template #default="{ row }">
            <el-tag v-if="row.zt == 0" type="success">正常</el-tag>
            <el-tag type="danger" v-else> 需修改</el-tag>
          </template>
        </el-table-column>




        <el-table-column label="操作" width="350" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
            <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
            <el-button v-if="row.zt === 1" type="success" link @click="handleOptimize(row)">
              一键优化
            </el-button>
            <el-button type="info" link @click="copyId(row.id)">复制id</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination v-model:current-page="pagination.current" v-model:page-size="pagination.size"
        :page-sizes="[10, 20, 50, 100]" :total="pagination.total" layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px" @close="handleDialogClose">
      <el-form ref="formRef" :model="form" label-width="80px">
        <el-form-item label="插入项id" prop="insertId">
          <el-input v-model="form.insertId" placeholder="请输入插入项id（可选）" />
        </el-form-item>
        <el-form-item label="文件上传">
          <el-upload :data="uploaddata" class="upload-demo" drag :action="uploadUrl" :headers="uploadHeaders"
            :on-success="handleUploadSuccess" :on-error="handleUploadError" :before-upload="beforeUpload" multiple
            :limit="100" :file-list="fileList">
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">
              拖拽文件到此处或 <em>点击上传</em>
            </div>
            <template #tip>
              <div class="el-upload__tip">
                支持 jpg、png、gif、bmp、webp 格式文件，单个文件不超过 10MB，最多可上传100个文件
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">
            完成
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑对话框 -->
    <el-dialog v-model="editDialogVisible" title="编辑数据" width="500px" @close="handleEditDialogClose">
      <el-form ref="editFormRef" :model="editForm" :rules="editRules" label-width="80px">
        <el-form-item label="年月" prop="mon">
          <el-input v-model="editForm.mon" placeholder="请输入年月" />
        </el-form-item>
        <el-form-item label="天" prop="da">
          <el-input v-model="editForm.da" placeholder="请输入天" />
        </el-form-item>
        <el-form-item label="金额" prop="pay">
          <el-input v-model="editForm.pay" placeholder="请输入金额" />
        </el-form-item>
        <el-form-item label="起点" prop="a">
          <el-input v-model="editForm.a" placeholder="请输入起点" />
        </el-form-item>
        <el-form-item label="起点补充" prop="d">
          <el-input v-model="editForm.d" placeholder="请输入起点补充" />
        </el-form-item>
        <el-form-item label="渠道" prop="qud">
          <el-input v-model="editForm.qud" placeholder="请输入渠道" />
        </el-form-item>
        <el-form-item label="时间" prop="tim">
          <el-input v-model="editForm.tim" placeholder="请输入时间" />
        </el-form-item>
        <el-form-item label="终点" prop="b">
          <el-input v-model="editForm.b" placeholder="请输入终点" />
        </el-form-item>
        <el-form-item label="终点补充" prop="c">
          <el-input v-model="editForm.c" placeholder="请输入c" />
        </el-form-item>
        <el-form-item label="支付方式" prop="zf">
          <el-input v-model="editForm.zf" placeholder="请输入支付方式" />
        </el-form-item>
        <el-form-item label="状态" prop="zt">
          <el-select v-model="editForm.zt" placeholder="请选择状态">
            <el-option :value="0" label="正常" />
            <el-option :value="1" label="需修改" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleEditSubmit" :loading="editSubmitLoading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { manageclient, deleteAll, updateclient, deleteclient } from '@/api/user'
import { UploadFilled } from '@element-plus/icons-vue'
import { initRouter } from "@/router/utils";

// 响应式数据
const loading = ref(false)
const tableData = ref([])
const dialogVisible = ref(false)
const dialogType = ref('add')
const dialogTitle = ref('新增用户')
const submitLoading = ref(false)
const formRef = ref()
const optimizeAllLoading = ref(false)
initRouter()
// 编辑对话框相关
const editDialogVisible = ref(false)
const editSubmitLoading = ref(false)
const editFormRef = ref()


const uploaddata = ref({
  to: 'hdasdkhshnadsgdhujakduiosn',
  id: '' // 插入项id
})
// 分页数据
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 搜索表单
const searchForm = reactive({
  status: null,
  dataStatus: null,
  keyword: ''
})

// 文件上传相关
const uploadUrl = 'http://121.229.145.213:30799/fortest/image2'
const uploadHeaders = ref({
  // 如果需要token，可以在这里添加
  // Authorization: 'Bearer ' + getToken()
})
const fileList = ref([])

// 表单数据 - 简化，因为现在是文件上传
const form = reactive({
  id: '',
  insertId: '' // 插入项id
})

// 编辑表单数据
const editForm = reactive({
  id: '',
  mon: '',
  pay: '',
  a: '',
  d: '',
  qud: '',
  tim: '',
  b: '',
  c: '',
  da: '',
  zf: '',
  zt: 0
})

// 表单验证规则 - 简化
const rules = {}

// 编辑表单验证规则
const editRules = {
  mon: [
    { required: false, trigger: 'blur' }
  ],
  pay: [
    { required: false, trigger: 'blur' }
  ],
  a: [
    { required: false, trigger: 'blur' }
  ],
  d: [
    { required: false, trigger: 'blur' }
  ],
  qud: [
    { required: false, trigger: 'blur' }
  ],
  tim: [
    { required: false, trigger: 'blur' }
  ],
  b: [
    { required: false, trigger: 'blur' }
  ],
  c: [
    { required: false, trigger: 'blur' }
  ],
  da: [
    { required: false, trigger: 'blur' }
  ],
  zf: [
    { required: false, trigger: 'blur' }
  ],
  zt: [
    { required: false, trigger: 'change' }
  ]
}

// 分页数据获取列表数据
const getList = async () => {
  loading.value = true
  try {
    const params = {
      index: pagination.current,
      size: pagination.size,
      to: 'hdasdkhshnadsgdhujakduiosn',
      mon: searchForm.keyword || '', // 关键词搜索
      zf: searchForm.status !== null ? (searchForm.status == '全部订单' ? '' : searchForm.status) : '',  // 订单状态筛选
      zt: searchForm.dataStatus !== null ? (searchForm.dataStatus == -1 ? '' : searchForm.dataStatus) : '',  // 数据状态筛选
    }
    const res = await manageclient(params)
    console.log(res)

    if (res.result && res.page) {
      tableData.value = res.result || []
      pagination.total = res.page.total || 0

      // 处理逻辑：
      // 1. 当除c和d字段外的其他字段为空时，将状态改为1
      // 2. 当c或d字段存在值时，状态也设为1
      // 3. 如果所有字段都有值且c、d字段为空，则状态改为0
      tableData.value.forEach(item => {
        const hasEmptyField = (
          !item.mon || item.mon === '' || item.mon === null ||
          !item.pay || item.pay === '' || item.pay === null ||
          !item.da || item.da === '' || item.da === null ||
          !item.a || item.a === '' || item.a === null ||
          !item.qud || item.qud === '' || item.qud === null ||
          !item.tim || item.tim === '' || item.tim === null ||
          !item.b || item.b === '' || item.b === null ||
          !item.zf || item.zf === '' || item.zf === null
        )

        const hasCOrDValue = (
          (item.c && item.c !== '' && item.c !== null) ||
          (item.d && item.d !== '' && item.d !== null)
        )

        const hasSpecialPay = (
          item.pay &&
          item.pay.toString().includes('特快专属奖')
        )

        if (hasEmptyField || hasCOrDValue || hasSpecialPay) {
          item.zt = 1
        } else {
          // 如果所有字段都有值且c、d字段为空，且金额不包含特快专属奖，则状态改为0
          item.zt = 0
        }
      })
      console.log('处理后数据:', tableData.value)

      // 强制触发响应式更新
      tableData.value = [...tableData.value]

    } else {
      tableData.value = []
      pagination.total = 0
    }
  } catch (error) {
    console.error('获取列表失败:', error)
    ElMessage.error('获取列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  getList()
}

// 重置
const handleReset = () => {
  searchForm.status = null
  searchForm.dataStatus = null
  searchForm.keyword = ''
  handleSearch()
}

// 分页大小改变
const handleSizeChange = (val) => {
  pagination.size = val
  getList()
}

// 当前页改变
const handleCurrentChange = (val) => {
  pagination.current = val
  getList()
}

// 新增
const handleAdd = () => {
  dialogType.value = 'add'
  dialogTitle.value = '文件上传'
  resetForm()
  dialogVisible.value = true
}

const handleClear = () => {
  let Q = {
    "id": "123456",
    "ids": "123456",
    "to": "hdasdkhshnadsgdhujakduiosn"
  }
  deleteAll(Q).then(res => {
    getList()
  })
}

// 编辑
const handleEdit = (row) => {
  editDialogVisible.value = true
  // 填充表单数据
  Object.assign(editForm, {
    id: row.id || '',
    mon: row.mon || '',
    pay: row.pay || '',
    a: row.a || '',
    d: row.d || '',
    qud: row.qud || '',
    tim: row.tim || '',
    b: row.b || '',
    c: row.c || '',
    da: row.da || '',
    zf: row.zf || '',
    zt: row.zt !== undefined ? row.zt : 0,
    fileSize: row.fileSize || '',
    fileType: row.fileType || 'image'
  })
}

// 提交编辑
const handleEditSubmit = async () => {
  if (!editFormRef.value) return

  await editFormRef.value.validate(async (valid) => {
    if (valid) {
      editSubmitLoading.value = true
      try {
        // 这里调用更新API
        const params = {
          id: editForm.id,
          mon: editForm.mon,
          pay: editForm.pay,
          a: editForm.a,
          d: editForm.d,
          qud: editForm.qud,
          tim: editForm.tim,
          b: editForm.b,
          c: editForm.c,
          da: editForm.da,
          zf: editForm.zf,
          zt: editForm.zt,
          fileSize: editForm.fileSize,
          fileType: editForm.fileType,
          to: 'hdasdkhshnadsgdhujakduiosn'
        }

        const res = await updateclient(params)
        console.log(res)
        ElMessage.success('编辑成功')
        editDialogVisible.value = false
        getList()

      } catch (error) {
        console.error('编辑失败:', error)
        ElMessage.error('编辑失败')
      } finally {
        editSubmitLoading.value = false
      }
    }
  })
}

// 编辑对话框关闭
const handleEditDialogClose = () => {
  if (editFormRef.value) {
    editFormRef.value.resetFields()
  }
}

// 编辑 查看文件
const handleView = (row) => {
  ElMessage.info(`查看文件: ${row.fileName}`)
  // 这里可以添加查看文件的逻辑，比如打开新窗口预览图片
  if (row.fileUrl) {
    window.open(row.fileUrl, '_blank')
  }
}

// 删除
const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该用户吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      let Q = {
        to: 'hdasdkhshnadsgdhujakduiosn',
        id: row.id,
      }

      await deleteclient(Q)
      ElMessage.success('删除成功')
      getList()
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => { })
}

// 处理单个数据优化（提取出单个优化逻辑）
const processSingleOptimize = async (row) => {
  // 需求一：如果年月、天、时间不存在，直接删除这一条
  if (!row.mon || !row.tim) {
    await deleteclient({ id: row.id, to: 'hdasdkhshnadsgdhujakduiosn' })
    return
  }

  // 创建优化后的数据副本
  const optimizedData = { ...row }
  let hasChanges = false

  // 需求二：处理金额字段
  const payStr = optimizedData.pay ? optimizedData.pay.toString().trim() : ''

  // 如果金额为空或包含"特快专属奖"，生成随机金额
  if (!payStr || payStr === '' || payStr.includes('特快专属奖')) {
    const randomAmount = (Math.floor(Math.random() * 50) + 1).toFixed(2)
    optimizedData.pay = randomAmount + '元'
    hasChanges = true
  } else {
    // 检查金额格式是否为'x.xx元'或'xx.xx元'格式
    const amountPattern = /^\d+\.\d{2}元$/

    if (!amountPattern.test(payStr)) {
      // 如果不是标准格式，修正为正确格式
      let numericValue = payStr.replace(/[^\d.]/g, '') // 提取数字和小数点

      if (numericValue && !isNaN(parseFloat(numericValue))) {
        // 转换为两位小数的格式并添加'元'
        const formattedAmount = parseFloat(numericValue).toFixed(2)
        optimizedData.pay = formattedAmount + '元'
        hasChanges = true
      } else {
        // 如果无法提取有效数字，生成随机金额
        const randomAmount = (Math.floor(Math.random() * 50) + 1).toFixed(2)
        optimizedData.pay = randomAmount + '元'
        hasChanges = true
      }
    }
  }

  // 需求三：如果渠道不存在，按概率随机赋值
  if (!optimizedData.qud || optimizedData.qud === '') {
    const channelOptions = [
      { name: '特惠快车', probability: 0.3 },
      { name: '快车', probability: 0.3 },
      { name: '滴滴特快', probability: 0.15 },
      { name: '接站单', probability: 0.1 },
      { name: '随心接', probability: 0.1 },
      { name: '拼车', probability: 0.05 }
    ]

    let random = Math.random()
    let selectedChannel = channelOptions[channelOptions.length - 1].name

    for (const channel of channelOptions) {
      if (random < channel.probability) {
        selectedChannel = channel.name
        break
      }
      random -= channel.probability
    }

    optimizedData.qud = selectedChannel
    hasChanges = true
  }

  // 需求四：处理支付/取消字段
  if (!optimizedData.zf || optimizedData.zf !== '已支付') {
    // 当支付/取消不存在或不等于已支付时，改为已支付
    optimizedData.zf = '已支付'
    hasChanges = true
  }

  // 需求五：如果时间存在，判断时间是否在06:00-22:00之间
  if (optimizedData.tim && optimizedData.tim !== '') {
    const timeStr = optimizedData.tim.toString()

    // 处理各种时间格式
    let hour = 0
    if (timeStr.includes(':')) {
      // 格式如 "14:30"
      hour = parseInt(timeStr.split(':')[0])
    } else if (timeStr.length === 4) {
      // 格式如 "1430"
      hour = parseInt(timeStr.substring(0, 2))
    } else if (timeStr.length === 3) {
      // 格式如 "930"
      hour = parseInt(timeStr.substring(0, 1))
    } else if (timeStr.length <= 2) {
      // 格式如 "14"
      hour = parseInt(timeStr)
    }

    // 如果时间在06:00-22:00之外，删除c和d字段
    if (hour < 6 || hour >= 22) {
      optimizedData.c = ''
      optimizedData.d = ''
      hasChanges = true
    }
  }

  // 需求六：处理a、b、c、d字段的逻辑
  // 规则1：当a、b、c、d字段都不存在时，按概率随机赋值
  if ((!optimizedData.a || optimizedData.a === '') &&
    (!optimizedData.b || optimizedData.b === '') &&
    (!optimizedData.c || optimizedData.c === '') &&
    (!optimizedData.d || optimizedData.d === '')) {

    const randomValue = Math.random()
    if (randomValue < 0.3) {
      optimizedData.a = '机场'
      optimizedData.b = '火车站'
    } else if (randomValue < 0.6) {
      optimizedData.a = '商业区'
      optimizedData.b = '住宅区'
    } else {
      optimizedData.a = '学校'
      optimizedData.b = '医院'
    }

    // 清空c、d字段
    optimizedData.c = ''
    optimizedData.d = ''
    hasChanges = true
  }

  // 规则2：当a、b、c、d都有值时的处理
  else if ((optimizedData.a && optimizedData.a !== '') &&
    (optimizedData.b && optimizedData.b !== '') &&
    (optimizedData.c && optimizedData.c !== '') &&
    (optimizedData.d && optimizedData.d !== '')) {

    // 新逻辑：a = a + b, b = c + d, c = '', d = ''
    optimizedData.a = optimizedData.a + optimizedData.b
    optimizedData.b = optimizedData.c + optimizedData.d
    optimizedData.c = ''
    optimizedData.d = ''
    hasChanges = true
  }

  // 规则3：当a、b、d有值时的处理
  else if ((optimizedData.a && optimizedData.a !== '') &&
    (optimizedData.b && optimizedData.b !== '') &&
    (!optimizedData.c || optimizedData.c === '') &&
    (optimizedData.d && optimizedData.d !== '')) {

    // 新逻辑：a = a, b = b + d, c = '', d = ''
    optimizedData.a = optimizedData.a // 保持不变
    optimizedData.b = optimizedData.b + optimizedData.d
    optimizedData.c = ''
    optimizedData.d = ''
    hasChanges = true
  }

  // 规则4：当a、b、c存在值而d无值时的处理
  else if ((optimizedData.a && optimizedData.a !== '') &&
    (optimizedData.b && optimizedData.b !== '') &&
    (optimizedData.c && optimizedData.c !== '') &&
    (!optimizedData.d || optimizedData.d === '')) {

    // 判断b的字符串长度
    if (optimizedData.b.length < 5) {
      // b长度小于5：a = a + b, b = c
      optimizedData.a = optimizedData.a + optimizedData.b
      optimizedData.b = optimizedData.c
    } else {
      // b长度大于等于5：a = a, b = b + c
      optimizedData.a = optimizedData.a // 保持不变
      optimizedData.b = optimizedData.b + optimizedData.c
    }

    // 清空c、d字段
    optimizedData.c = ''
    optimizedData.d = ''
    hasChanges = true
  }

  // 新需求：处理'天'字段的逻辑
  // 从当前数据往上找最近一条存在'天'字段的数据进行对比
  if (!optimizedData.da || optimizedData.da === '') {
    try {
      // 获取所有数据，用于查找上一条数据
      const allDataParams = {
        index: 1,
        size: 9999, // 获取所有数据
        to: 'hdasdkhshnadsgdhujakduiosn'
      }
      const allRes = await manageclient(allDataParams)
      const allData = allRes.result || []

      // 找到当前数据在数组中的位置
      const currentIndex = allData.findIndex(item => item.id === row.id)

      if (currentIndex > 0) {
        // 往上查找最近一条存在'天'字段的数据
        let previousData = null
        for (let i = currentIndex - 1; i >= 0; i--) {
          if (allData[i] && allData[i].da && allData[i].da !== '' && allData[i].tim && allData[i].tim !== '') {
            previousData = allData[i]
            break
          }
        }

        if (previousData) {
          // 解析上一条数据的时间
          const prevTimeStr = previousData.tim.toString()
          const prevTime = parseInt(prevTimeStr.replace(':', ''))

          // 解析当前数据的时间
          const currTimeStr = optimizedData.tim.toString()
          const currTime = parseInt(currTimeStr.replace(':', ''))

          // 获取上一条数据的'天'字段值
          const prevDa = previousData.da

          // 提取日期部分（假设格式为'MM月DD日'）
          const dateMatch = prevDa.match(/(\d+)月(\d+)日/)
          if (dateMatch) {
            let month = parseInt(dateMatch[1])
            let day = parseInt(dateMatch[2])

            // 根据时间比较决定日期
            if (prevTime < currTime) {
              // 上一条时间小于当前时间，保持相同日期
              optimizedData.da = prevDa
            } else {
              // 上一条时间大于当前时间，日期减1天
              day = day - 1
              if (day <= 0) {
                // 如果减1天后天数小于等于0，需要处理月份和天数
                month = month - 1
                if (month <= 0) month = 12
                day = 30 // 简化为30天，可以根据实际月份调整
              }

              // 格式化新的日期
              optimizedData.da = `${month.toString().padStart(2, '0')}月${day.toString().padStart(2, '0')}日`
            }
          } else {
            // 如果无法解析日期格式，使用上一条数据的日期
            optimizedData.da = prevDa
          }

          hasChanges = true
        } else {
          // 如果往上找不到有'天'字段的数据，保持为空（不处理）
          // optimizedData.da 保持原值（空）
        }
      } else {
        // 如果是第一条数据，保持为空（不处理）
        // optimizedData.da 保持原值（空）
      }
    } catch (error) {
      console.error('处理天字段失败:', error)
      // 失败时保持原值（空）
    }
  }

  // 当a或b无值时，从其他页获取状态为0的数据
  if (!optimizedData.a || optimizedData.a === '' ||
    !optimizedData.b || optimizedData.b === '') {
    try {
      const currentPage = pagination.current || 1
      const totalPages = Math.ceil(pagination.total / pagination.size) || 10

      // 计算获取页面的策略：如果当前页是前一半，获取后一半的页码
      let targetPage
      if (currentPage <= totalPages / 2) {
        targetPage = Math.floor(Math.random() * (totalPages - Math.floor(totalPages / 2))) + Math.floor(totalPages / 2) + 1
      } else {
        targetPage = Math.floor(Math.random() * Math.floor(totalPages / 2)) + 1
      }

      // 获取其他页的数据
      const params = {
        index: targetPage,
        size: pagination.size || 10,
        to: 'hdasdkhshnadsgdhujakduiosn'
      }
      const res = await manageclient(params)
      const response = { data: res.result || [] }

      if (response.data && response.data.length > 0) {
        // 筛选状态为0的数据
        const validData = response.data.filter(item => item.zt === 0)
        if (validData.length > 0) {
          const randomData = validData[Math.floor(Math.random() * validData.length)]

          // 赋值给当前记录
          if (!optimizedData.a || optimizedData.a === '') {
            optimizedData.a = randomData.a || ''
          }
          if (!optimizedData.b || optimizedData.b === '') {
            optimizedData.b = randomData.b || ''
          }
          hasChanges = true
        }
      }
    } catch (fetchError) {
      console.error('获取其他页数据失败:', fetchError)
      // 静默失败，不影响主流程
    }
  }

  // 最后统一提交修改
  if (hasChanges) {
    const params = {
      id: optimizedData.id,
      mon: optimizedData.mon,
      pay: optimizedData.pay,
      a: optimizedData.a,
      d: '',
      qud: optimizedData.qud,
      tim: optimizedData.tim,
      b: optimizedData.b,
      c: '',
      zf: optimizedData.zf,
      zt: 0,
      da: optimizedData.da,
      to: 'hdasdkhshnadsgdhujakduiosn'
    }

    await updateclient(params)
  } else {
    // 如果没有需要优化的内容，直接更新状态
    const params = {
      id: row.id,
      zt: 0,
      to: 'hdasdkhshnadsgdhujakduiosn'
    }
    await updateclient(params)
  }
}

// 一键优化
const handleOptimize = async (row) => {
  // 需求一：如果年月、天、时间不存在，直接删除这一条
  if (!row.mon || !row.tim) {
    ElMessageBox.confirm('该记录缺少必要信息（年月、时间），确定要删除吗？', '删除确认', {
      confirmButtonText: '确定删除',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      try {
        await deleteclient({ id: row.id, to: 'hdasdkhshnadsgdhujakduiosn' })
        ElMessage.success('记录已删除')
        getList()
      } catch (error) {
        console.error('删除失败:', error)
        ElMessage.error('删除失败')
      }
    }).catch(() => { })
    return
  }

  try {
    await processSingleOptimize(row)
    ElMessage.success('一键优化成功')
    getList()
  } catch (error) {
    console.error('一键优化失败:', error)
    ElMessage.error('一键优化失败')
  }
}

// 一键优化全部
const handleOptimizeAll = async () => {
  if (!tableData.value || tableData.value.length === 0) {
    ElMessage.warning('当前页没有数据需要优化')
    return
  }

  // 创建进度弹框
  const progressMessage = ElMessage({
    message: `正在优化第 0/${tableData.value.length} 条数据...`,
    duration: 0,
    type: 'info',
    showClose: false
  })

  try {
    optimizeAllLoading.value = true
    let successCount = 0
    let errorCount = 0

    // 逐个处理当前页的所有数据
    for (let i = 0; i < tableData.value.length; i++) {
      const row = tableData.value[i]
      const currentIndex = i + 1

      // 更新进度
      progressMessage.message = `正在优化第 ${currentIndex}/${tableData.value.length} 条数据...`

      try {
        await processSingleOptimize(row)
        successCount++
      } catch (error) {
        console.error(`优化数据 ${row.id} 失败:`, error)
        errorCount++
      }
    }

    // 完成后刷新列表
    await getList()

    // 关闭进度弹框
    progressMessage.close()

    if (errorCount === 0) {
      ElMessage.success(`一键优化完成，成功优化 ${successCount} 条数据`)
    } else {
      ElMessage.warning(`一键优化完成，成功 ${successCount} 条，失败 ${errorCount} 条`)
    }
  } catch (error) {
    // 关闭进度弹框
    progressMessage.close()
    console.error('一键优化全部失败:', error)
    ElMessage.error('一键优化全部失败')
  } finally {
    optimizeAllLoading.value = false
  }
}

// 文件上传相关方法

// 上传前校验
const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt10M = file.size / 1024 / 1024 < 10
  
  // 上传前将表单中的插入项id赋值给上传数据
  if (form.insertId) {
    uploaddata.value.id = form.insertId
  } else {
    uploaddata.value.id = '' // 如果没有输入id，设为空
  }
  
  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt10M) {
    ElMessage.error('文件大小不能超过 10MB!')
    return false
  }
  return true
}

// 上传成功回调
  const handleUploadSuccess = (response, file, fileList) => {
    // 所有文件上传完成后刷新列表但不关闭弹窗
    const allUploaded = fileList.every(f => f.status === 'success')
    if (allUploaded) {
      ElMessage.success('文件上传完成')
      fileList.value = []
      getList()
    }
  }

// 上传失败回调
const handleUploadError = (error, file, fileList) => {
  ElMessage.error('文件上传失败')
}

// 提交表单 - 文件上传完成后的处理
  const handleSubmit = () => {
    // 手动点击完成按钮时刷新列表但不关闭弹窗
    getList()
  }

// 复制id到剪贴板
const copyId = (id) => {
  navigator.clipboard.writeText(id).then(() => {
    ElMessage.success('ID已复制到剪贴板')
  }).catch(() => {
    ElMessage.error('复制失败，请手动复制')
  })
}

// 重置表单
const resetForm = () => {
  form.id = ''
  form.username = ''
  form.name = ''
  form.password = ''
  form.qx = 2
  form.insertId = '' // 重置插入项id
}

// 对话框关闭
const handleDialogClose = () => {
  formRef.value?.resetFields()
  fileList.value = []
  getList()
  resetForm()
}

// 页面加载时获取数据
onMounted(() => {
  getList()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.el-pagination {
  margin-top: 20px;
  justify-content: flex-end;
}
</style>